package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/category")
@Slf4j
public class CategoryController {
    @Autowired
    private CategoryService categoryService;

    @PostMapping
    @CacheEvict(cacheNames = "category" ,allEntries = true)
    public R save(@RequestBody Category category) {
        log.info("增加了:{}", category);

        categoryService.save(category);
        return R.success("新增分类成功");
    }//增

    @GetMapping("/page")
    @Cacheable(cacheNames = "category",key = "#page+'_'+#pageSize")
    public R page(Integer page, Integer pageSize) {
        //分页构造器
        IPage<Category> pageInfo = new Page<>(page, pageSize);
        //条件构造器
        LambdaQueryWrapper<Category> lwq = new LambdaQueryWrapper<>();
        //添加排序条件，根据sort进行排序
        lwq.orderByAsc(Category::getSort);
        //分页查询
        categoryService.page(pageInfo, lwq);

        return R.success(pageInfo);
    }

    @DeleteMapping
    @CacheEvict(cacheNames = "category" ,allEntries = true)
    public R delete(Long id) {
        log.info("要删除的是{}",id);
        categoryService.deleteById(id);
        return R.success("删除成功");
    }


    @PutMapping
    @CacheEvict(cacheNames = "category" ,allEntries = true)
    public R update(@RequestBody Category category) {
        log.info("要修改的是{}", category);
        categoryService.updateById(category);
        return R.success("修改分类信息成功");
    }


    @GetMapping("/list")
    @Cacheable(cacheNames = "category",key = "#category.type")
    public R list(Category category) {
        // 疑问,明明是get请求的路径参数,为什么会以对象来接受,还不是json的形式???
        LambdaQueryWrapper<Category> lqw = new LambdaQueryWrapper<>();
        // 根据type找对应的内容
        lqw.eq(category.getType() != null,Category::getType, category.getType());
        //添加排序条件
        lqw.orderByAsc(Category::getSort).orderByDesc(Category::getUpdateTime);
        List<Category> list = categoryService.list(lqw);

        return R.success(list);
    }


}
